package com.n4v1.pko.server.model.map;

import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.tiled.TiledMapPlus;

public class StandardMap implements Map {
	
	private TiledMapPlus tiledMap;
	private boolean[][] blockedAreas;
	
	public StandardMap(String filePath) throws SlickException {
		tiledMap = new TiledMapPlus(filePath);
		this.iniBlockAreas();
	}
	
	public void iniBlockAreas() throws SlickException {
		blockedAreas = new boolean[tiledMap.getWidth()][tiledMap.getHeight()];
		int collisionLayerID = tiledMap.getLayerIndex("collisions");
		for (int x=0;x<tiledMap.getWidth();x++) {
			for (int y=0;y<tiledMap.getHeight();y++) {
				int tileID = tiledMap.getTileId(x, y, collisionLayerID);
				String value = tiledMap.getTileProperty(tileID, "blocked", "0");
				if ("1".equals(value)) {
					blockedAreas[x][y] = true;
				}
			}
		}
	}

	@Override
	public boolean isBlocked(Rectangle obj) {
		boolean blocked = false;
		int x1, y1, x2, y2;
		float[] points = obj.getPoints();
		
		for(int i = 1; i < points.length && !blocked; i += 2) {
			x1 = (int)(points[i-1] + 0.5);
			y1 = (int)(points[i] + 0.5);
			x2 = (int)(points[i-1] - 0.5);
			y2 = (int)(points[i] - 0.5);
			if(this.isBlockedAt(x1, y1) || this.isBlockedAt(x2, y1) ||
					this.isBlockedAt(x1, y2) || this.isBlockedAt(x2, y2))
				blocked = true;
		}
		return blocked;
	}

	public boolean isBlockedAt(int x, int y) {
		return blockedAreas[x][y];
	}

}
